import dva from 'dva';
import {voteSearch} from '../services/vote';

export default {
  namespace: 'votes',
  state: {
    list: [],
    loading: true,
    total: 0
  },
  reducers: {
    save(state, {payload: {data: data}}) {
      return {...state, ...data.data, ...{loading: false}};
    },
    startLoading(state, {payload: {}}){
      return {...state, ...{loading:true}};
    }
  },
  effects: {
    *fetch({payload: query}, {call, put}) {
      const {data} = yield call(voteSearch, query);
      yield put({type: 'save', payload: {data: data}});
    }
  },
  subscriptions: {
    setup({dispatch, history}) {
      return history.listen(({pathname, query}) => {
        if (pathname === '/votes') {
          dispatch({type: 'fetch', payload: query});
        }
      });
    }
  }
};
